<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;

class AdController extends BaseController
{
    //

    public function getTarget(Request $request)
    {
    	$adPosition = $request->input('ad_position');
    	$imei = $request->input('imei');
        $ip = $request->input('ip');
        $lat = $request->input('lat');
        $lon = $request->input('lon');
        $lac = $request->input('lac');
        $city = $request->input('city');
        $m2 = $request->input('m2');
        $cityCode = $request->input('city_code');
        if (empty($imei)) {
            $imei = md5(uniqid() . time());
        }
        if (empty($adPosition)) {
            $response = [
                'code'  =>  -1,
                'msg'   =>  'ad_position can not empty',
            ];
        } else {
            $displayOption = \App\Model\SysConfig::getAdDisplayOptionByPos($m2, $ip, $lat, $lon, $city ,$lac);
            $cpcLimit = new \App\Model\CpcLimit($imei, $adPosition);
        	$source = $cpcLimit->getDeviceTarget();
        	$response = [
        		'code'	=>	0,
        		'msg'	=>	'OK',
        		'data'	=>	[
        			'source'	=>	$source,
                    'display_option'    =>  $displayOption,
                    'need_refresh'  =>  \App\Model\SysConfig::getAdRefresh(),
        		],
        	];
        }

    	return response()->json($response);
    }

    public function getAd(Request $request)
    {
        $realKey = "ads:youkantou";
        $redis = app('redis')->connection('default');
        $hKeys = $redis->hKeys($realKey);
        $arrKey = array_rand($hKeys);
        $hKey = $hKeys[$arrKey];
        $data = $redis->hGet($realKey, $hKey);
        return response()->json([
            'code'  =>  0,
            'msg'   =>  'OK',
            'data'  =>  [
                'adList'    =>  [json_decode($data, true)],
            ],
        ]);
    }
}
